package top.hepingan.java.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.hepingan.java.common.Result;
import top.hepingan.java.entity.*;
import top.hepingan.java.entity.dto.*;
import top.hepingan.java.mapper.AstudentGroupadminMapper;
import top.hepingan.java.mapper.AstudentUserMapper;
import top.hepingan.java.mapper.PeizhibiaoMapper;
import top.hepingan.java.service.*;

import java.beans.Transient;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;


@RequestMapping("/user")
@RestController
@Slf4j

public class Test {
    @Autowired
    private IAstudentUserService astudentUserService;

/// //////////////////////////////////////////////////
@Autowired
IAstudentGroupService gstudentGroupService;
@Autowired
IAstudentGroupadminService gstudentGroupadminService;


    //**小组功能 创建小组 加入小组(list) 分享小组 显示小组
    @GetMapping("/group/id")
    public Result group() {
        if (StpUtil.isLogin()) {
            Long loginId = StpUtil.getLoginIdAsLong();
            groupa  groupa= new groupa();

            if (loginId == null) {
                return Result.error("请先登录");
            }
            groupa.setUserId(loginId);
            LambdaQueryWrapper<AstudentGroupadmin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AstudentGroupadmin::getXzAdminUserid, loginId);
            AstudentGroupadmin astudentGroupadmin =      gstudentGroupadminService.getOne(lambdaQueryWrapper);
           //管理员admin
            if (astudentGroupadmin != null) {
                /// 显示组员 提供踢出 提供解散 提供改名
                groupa.setIsbool("admin");
                groupa.setAstudentGroupadmin(astudentGroupadmin);
                /// 显示小组
                LambdaQueryWrapper<AstudentGroup> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(AstudentGroup::getCreatedByUserId, astudentGroupadmin.getId());
                /// 显示组员
                List<AstudentGroup> list = gstudentGroupService.list(lambdaQueryWrapper1);
        List< AstudentGroupDto> l = list.stream().map( item -> {
                    AstudentGroupDto astudentGroupDto = new AstudentGroupDto();
                    BeanUtils.copyProperties(item, astudentGroupDto);
                    AstudentUser aqqq = astudentUserService.getById(item.getUserId());
                    astudentGroupDto.setUsername(aqqq.getUsername());
                    return astudentGroupDto;
                }).toList();
               groupa.setList(l);
        return  Result.ok().setData(groupa);
            }
            /// 查询小组
            LambdaQueryWrapper<AstudentGroup> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(AstudentGroup::getUserId, loginId);
            AstudentGroup astudentGroup = gstudentGroupService.getOne(lambdaQueryWrapper1);
            if (astudentGroup != null) {
                //加入小组 展示组长 提供退出功能
                groupa.setIsbool("user");
                //查询组长
                LambdaQueryWrapper<AstudentGroupadmin> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(AstudentGroupadmin::getId, astudentGroup.getCreatedByUserId());
                //查询到了--展示组员
                AstudentGroupadmin astudentGroupadmin1 = gstudentGroupadminService.getOne(lambdaQueryWrapper2);
               //组员
                LambdaQueryWrapper< AstudentGroup> lq=new LambdaQueryWrapper<>();
                lq.eq(AstudentGroup::getCreatedByUserId,astudentGroupadmin1.getId());
                List<AstudentGroup> list = gstudentGroupService.list(lq);
                //给名字
                List< AstudentGroupDto>li=list.stream().map( item -> {
                    AstudentGroupDto astudentGroupDto = new AstudentGroupDto();
                    BeanUtils.copyProperties(item, astudentGroupDto);
                   AstudentUser aqqq = astudentUserService.getById(item.getUserId());
                   astudentGroupDto.setUsername(aqqq.getUsername());
                   return astudentGroupDto;
                }).toList();
                groupa.setList(li);
                groupa.setAstudentGroupadmin(astudentGroupadmin1);
                groupa.setIsbool("user");
                return Result.ok().setData(groupa);
            } else {
                //未加入小组-提供加入小组功能--提供展示所有小组
                List<AstudentGroupadmin> list = gstudentGroupadminService.list();
                groupa.setIsbool("0");
                groupa.setList1(list);
                return Result.ok().setData(groupa);
            }

        } else {
            return Result.error("请先登录");
        }

    }
    /// 角色0 加入小组和创建小组
    //加入小组
    @GetMapping("/group/join")
    public Result joinGroup(int groupId)
    {
        if (StpUtil.isLogin()) {
            Long loginId = StpUtil.getLoginIdAsLong();
            if (loginId == null) {
                return Result.error("请先登录");
            }
            //不做校验了，让你直接加
            AstudentGroupadmin astudentGroup =  gstudentGroupadminService.getById(groupId);
            if (astudentGroup != null) {
                AstudentGroup astudentGroup1 = new AstudentGroup();
                astudentGroup1.setCreatedByUserId(astudentGroup.getId());
                astudentGroup1.setUserId(Math.toIntExact(loginId));
                astudentGroup1.setGroupName(astudentGroup.getXzName());
                if (gstudentGroupService.save(astudentGroup1)) {
                    return Result.ok("加入成功");

                } else {
                    return Result.error("加入失败");
                }

            }else
            {
                return Result.error("小组不存在");
            }
        }else
        {
            return Result.error("请先登录");
        }

    }
    //管理员删除小组

    //退出

    //创建小组

    @GetMapping("/group/create")
    public Result createGroup(@RequestParam String groupName, @RequestParam String username) {
                        if (StpUtil.isLogin()) {
            Long loginId = StpUtil.getLoginIdAsLong();
            if (loginId == null) {
                return Result.error("请先登录");
            }
            AstudentGroupadmin groupgroup = new AstudentGroupadmin();
            groupgroup.setXzName(groupName);
            groupgroup.setXzAdminUserid(Math.toIntExact(loginId));
      AstudentUser astudentUser =  astudentUserService.getById(loginId);
            groupgroup.setXzAdminName(astudentUser.getUsername());
            if (gstudentGroupadminService.save(groupgroup)) {
                return Result.ok("创建成功");
            }
        }
        return Result.error("请先登录");
    }
    //组长踢人
    @GetMapping("/group/kick")
    public Result kickGroup(int userId) {
        if (StpUtil.isLogin()) {
            Long loginId = StpUtil.getLoginIdAsLong();
            if (loginId == null) {
                return Result.error("请先登录");
            }
            //查询userid所在小组

            LambdaQueryWrapper<AstudentGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AstudentGroup::getUserId, userId);
            AstudentGroup astudentGroup = gstudentGroupService.getOne(lambdaQueryWrapper);

            //查询userid 是否对应
            AstudentGroupadmin astudentGroupadmin =     gstudentGroupadminService.getById(astudentGroup.getCreatedByUserId());
         Integer xzAdminUserid =     astudentGroupadmin.getXzAdminUserid();
         if (xzAdminUserid==Math.toIntExact(loginId)) {
             LambdaQueryWrapper<AstudentGroup> lam= new LambdaQueryWrapper<>();
             lam.eq(AstudentGroup::getUserId, userId);
             if (gstudentGroupService.remove(lam)) {
                 return Result.ok("删除成功");
             } else {
                 return Result.error("删除失败");
             }
         }
            return Result.error("只有组长才能踢人");
        }else {
            return Result.error("请先登录");
        }


    }













    @PostMapping("/group/leave")
    public Result leaveGroup() {
        if (StpUtil.isLogin()) {
            Long loginId = StpUtil.getLoginIdAsLong();
            if (loginId == null) {
                return Result.error("请先登录");
            }

            LambdaQueryWrapper<AstudentGroupadmin> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(AstudentGroupadmin::getXzAdminUserid, loginId);
            AstudentGroupadmin astudentGroupadmin = gstudentGroupadminService.getOne(lambdaQueryWrapper1);
            if (astudentGroupadmin != null) {
                //管理员删除
                if (gstudentGroupadminService.removeById(astudentGroupadmin.getId())) {
                    return Result.ok("删除成功");
                } else {
                    return Result.error("删除失败");
                }
            }

            LambdaQueryWrapper<AstudentGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AstudentGroup::getUserId, loginId);
            if (gstudentGroupService.remove(lambdaQueryWrapper)) {
                return Result.ok("退出成功");
            } else {
                return Result.error("退出失败");
            }
        } else {
            return Result.error("请先登录");
        }
    }




















    /// ///////////////////////////
    ///
    @Autowired
    private PeizhibiaoMapper peizhibiaoMapper;

 @PostMapping("/rank/regist")
    public Result regist(@RequestBody AstudentUser user) {
    Peizhibiao peizhibiao =    peizhibiaoMapper.selectById(1L);
     if(peizhibiao.getZhuceIs()==0)
     {
         return Result.error("注册功能已关闭");
     }
     //查询名字是否重复
     if (astudentUserService.getOne(new QueryWrapper<AstudentUser>().eq("username", user.getUsername())) != null) {
         return Result.error("用户名重复,请名字后新增数字");
     }else {
         user.setPassword(Md5Crypt.md5Crypt(user.getPassword().getBytes(),"$1$fixed123"));
         return astudentUserService.save(user) ? Result.ok("注册成功") : Result.error("注册失败");
     }


    }

    @PostMapping("/login")
    public Result login(@RequestBody AstudentUser user) {
        Peizhibiao peizhibiao =    peizhibiaoMapper.selectById(1L);
        if(peizhibiao.getZhuceIs()==0)
        {
            return Result.error("登录功能已关闭");
        }
        if (user == null || user.getUsername().equals("") || user.getPassword().equals("")) {
            return Result.error("用户名或密码不能为空");
        }
        LambdaQueryWrapper<AstudentUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AstudentUser::getUsername, user.getUsername());


        AstudentUser astudentUser = astudentUserService.getOne(lambdaQueryWrapper);
        String passwordMd5 =   Md5Crypt.md5Crypt(user.getPassword().getBytes(),"$1$fixed123");
        if (astudentUser != null && astudentUser.getPassword().equals(passwordMd5))  {
            StpUtil.login(astudentUser.getUserId());
            return Result.data(StpUtil.getTokenInfo());
        }

            return Result.error("用户名或密码错误");



    }

    /**
     * 排名展示
     * 返回前十名的叶子排行和阅读排行
     */
    @GetMapping("/rank/pm")
    public Result rank() {
        if (StpUtil.isLogin()) {
            Long loginId = StpUtil.getLoginIdAsLong();
            if (loginId == null) {
                return Result.error("请先登录");
            }
            LambdaQueryWrapper< AstudentLeafCount> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            /// /根据排序，从大到小拿取十个 只要十个
            lambdaQueryWrapper.orderByDesc(AstudentLeafCount::getLeafCount);
            lambdaQueryWrapper.last("limit 20");
            List<AstudentLeafCount> list = astudentLeafCountService.list(lambdaQueryWrapper);
            //查询用户名字
            pmlist list1 = new pmlist();

            List<AstudentLeafCountdto> list1a = list.stream().map( item -> {
                AstudentLeafCountdto a = new AstudentLeafCountdto();
                BeanUtils.copyProperties( item, a);
                AstudentUser byId = astudentUserService.getById(item.getUserId());
                a.setName(byId.getUsername());
                return a;
            }).toList();
            list1.setList1(list1a);
            list1.setUserid(loginId);
            return  Result.ok().setData(list1);
        } else {
            return Result.error("请先登录");
        }


    }






    /**
     * 返回总阅读数 本月印度数 连续阅读数
     * 请求  token解密用户id
     */
    @Autowired
    private IAstudentReadingLogService astudentReadingLogService;

    @PostMapping("ydts")
    public Result ydts() {
        if (StpUtil.isLogin()) {
            Long loginId = StpUtil.getLoginIdAsLong();
            if (loginId == null) {
                return Result.error("请先登录");
            }
            LambdaQueryWrapper<AstudentReadingLog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AstudentReadingLog::getUserId, loginId);
            List<AstudentReadingLog> list = astudentReadingLogService.list(lambdaQueryWrapper);
// 获取记录日志
            int count = 0;
            int consecutiveDays = 0;
            int currentMonthReadings = 0;
            count = list.size();
            if (list != null && !list.isEmpty()) {
                // 计算总数


                // // 假设第一天是连续阅读的天数
                list.sort(Comparator.comparing(record -> record.getCreatedAt().toLocalDate()));

                consecutiveDays = 1;
                for (int i = 0; i < list.size() - 1; i++) {
                    LocalDate current = list.get(i).getCreatedAt().toLocalDate();
                    LocalDate next = list.get(i + 1).getCreatedAt().toLocalDate();

                    // 判断是否是连续天
                    if (current.plusDays(1).isEqual(next)) {
                        consecutiveDays++;
                    } else if (!current.isEqual(next)) { // 断了就重置
                        consecutiveDays = 1;
                    }
                }
                // 计算本月阅读总数
                currentMonthReadings = 0;
                int currentMonth = list.get(0).getCreatedAt().getMonthValue(); // 获取第一条记录的月份
                for (int j = 0; j < list.size(); j++) {
                    if (list.get(j).getCreatedAt().getMonthValue() == currentMonth) {
                        // 如果是本月的记录，则增加阅读数
                        currentMonthReadings++;
                    }
                }
            }

            ydtsdto ydtsdto = new ydtsdto();
            ydtsdto.setCount(count);
            ydtsdto.setDay(consecutiveDays);
            ydtsdto.setReadThisMonth(currentMonthReadings);
            AstudentUser byId = astudentUserService.getById(loginId);
            ydtsdto.setUsername(byId.getUsername());
            ydtsdto.setTime(byId.getCreatedAt());

            return Result.ok().setData(ydtsdto);
        } else {
            return Result.error("请先登录");
        }


    }

    /**
     * 勋章列表查询
     * 查询我们拥有的徽章
     * 1.查询所有徽章
     * 2.对比，过滤我们有的勋章
     */
    @Autowired
    //勋章表
    private IAstudentBadgeidService astudentBadgeidService;
    //勋章记录表
    @Autowired
    private IAstudentBadgeService astudentBadgeService;

    @PostMapping("/list")
    public Result list() {
        if (StpUtil.isLogin()) {

            Long loginId = StpUtil.getLoginIdAsLong();
            if (loginId == null) {
                return Result.error("请先登录");
            }
            // 查询所有勋章记录（未获得的勋章） // 从数据库中获取所有勋章记录
            List<AstudentBadgeid> allBadges = astudentBadgeidService.list();

// 查询已经孩子已经获取到的勋章 // 从数据库中获取已经获得的勋章记录
            LambdaQueryWrapper<AstudentBadge> lambdaQueryWrapper = new LambdaQueryWrapper<>();

            lambdaQueryWrapper.eq(AstudentBadge::getUserId, loginId);

            List<AstudentBadge> obtainedBadges = astudentBadgeService.list(lambdaQueryWrapper);

// 汇总勋章记录，包括所有勋章ID以及对应的是否已获取的状态 // 用于存储汇总结果
            List<BadgeSummary> badgeSummaryList = new ArrayList<>();



// 遍历所有勋章记录
            for (AstudentBadgeid badgeid : allBadges) {
                // 查找当前勋章是否已经被获取
                Optional<AstudentBadge> obtainedBadge = obtainedBadges.stream()
                        .filter(b -> b.getStubadegeId().equals(badgeid.getId())) // 通过勋章id关联获取记录
                        .findFirst(); // 查找是否存在已获得的勋章记录

                // 如果已经获得，则标记为已获取，反之为未获取
                BadgeSummary badgeSummary = new BadgeSummary();
                badgeSummary.setBadgeName(badgeid.getBadegeName());
                badgeSummary.setLeafCount(badgeid.getLeafCount());
                badgeSummary.setTimeOut(badgeid.getTimeOut());
                //总勋章
                badgeSummary.setTotalLeafCount(allBadges.size());
                badgeSummary.setObtained(obtainedBadge.isPresent());
                //获得勋章
                badgeSummary.setObtainedLeafCount(obtainedBadges.size());
                badgeSummary.setObtainedLeafCount(obtainedBadges.size());
                // 如果已获得，设置获取时间
                obtainedBadge.ifPresent(b -> badgeSummary.setAwardDate(b.getAwardDate()));

                // 将汇总结果加入列表
                badgeSummaryList.add(badgeSummary);
            }
            return Result.data(badgeSummaryList);

        } else {
            return Result.error("请先登录");
        }



    }
    /**
     * 叶子数量查询
     */
    @Autowired
    private IAstudentLeafCountService astudentLeafCountService;
    @GetMapping("/yzsccount")
    public Result yzsccount() {
        if (StpUtil.isLogin()) {

            Long loginId = StpUtil.getLoginIdAsLong();
            if (loginId == null) {
                return Result.error("请先登录");
            }
            LambdaQueryWrapper<AstudentLeafCount> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AstudentLeafCount::getUserId,loginId);

            int count=astudentLeafCountService.getOne(lambdaQueryWrapper).getLeafCount();
            return  Result.data(count);
        }else
        {
            return Result.error("请先登录");

        }


    }
    /**
     * 阅读显示
     * http://localhost:9090/user/readxs?current=2&size=10
     */
     @GetMapping("/readxs")
     public Result readxs(int current,int size ) {
         if (StpUtil.isLogin()) {

             Long loginId = StpUtil.getLoginIdAsLong();
             if (loginId == null) {
                 return Result.error("请先登录");
             }
             //分页返回
             Page<AstudentReadingLog> page = new Page<>( current, size);
             astudentReadingLogService.page(page, new QueryWrapper<AstudentReadingLog>().eq("user_id", loginId));
             return Result.data(page);
         }else
         {
             return Result.error("请先登录");
         }
     }

    /**
     * 阅读创建
     * @param readingLogDto
     * @return
     */
     @PostMapping("/readlog/up")
     @Transient
     public Result readlogUp(@RequestBody AstudentReadingLog readingLogDto) {
         if (StpUtil.isLogin()) {
             Long loginId = StpUtil.getLoginIdAsLong();
             if (loginId == null) {
                 return Result.error("请先登录");
             }
             readingLogDto.setUserId(Math.toIntExact(loginId));
             if (astudentReadingLogService.save(readingLogDto)) {
                 //更新叶子树
                 LambdaQueryWrapper<AstudentLeafCount> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                 lambdaQueryWrapper.eq(AstudentLeafCount::getUserId,loginId);
                 AstudentLeafCount astudentLeafCount =   astudentLeafCountService.getOne(lambdaQueryWrapper);
                 if(astudentLeafCount==null)
                 {
                     astudentLeafCount=new AstudentLeafCount();
                     astudentLeafCount.setUserId(Math.toIntExact(loginId));
                     astudentLeafCountService.save(astudentLeafCount);
                     astudentLeafCount.setLeafCount(0);
                 }
                 astudentLeafCount.setLeafCount(astudentLeafCount.getLeafCount()+1);
                 astudentLeafCountService.updateById(astudentLeafCount);


                 return Result.ok("添加成功");
             } else {
                 return Result.error("添加失败");
             }
         }else
         {
             return Result.error("请先登录");
         }
     }
    /**
     * 获取勋章
     * 传递勋章名字  连续阅读天数
     * 是否能够得到，如果可以得到就插入数据库
     *
     */

    @PostMapping("/getbadge")
    public Result getbadge(@RequestBody catsdto catsdto) {
        //medal: %E5%B0%8F%E9%9B%A8%E4%B8%93%E5%B1%9E%E5%8B%8B%E7%AB%A0
        //lxydts: 0

        if (StpUtil.isLogin()) {
            Long loginId = StpUtil.getLoginIdAsLong();
            if (loginId == null) {
                return Result.error("请先登录");
            }
            LambdaQueryWrapper<AstudentBadgeid> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AstudentBadgeid::getBadegeName, catsdto.getMedal());
            //拿取勋章条件
            AstudentBadgeid astudentBadgeid =   astudentBadgeidService.getOne(lambdaQueryWrapper);
            //
            if(astudentBadgeid.getLeafCount()>0)
            {
                LambdaQueryWrapper<AstudentLeafCount> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(AstudentLeafCount::getUserId,loginId);
                AstudentLeafCount astudentLeafCount = astudentLeafCountService.getOne(lambdaQueryWrapper1);
                //查询用户叶子数--逆天if嵌套
                if(astudentBadgeid.getLeafCount()>astudentLeafCount.getLeafCount())
                {
                    return Result.error("叶子数不足");
                }
            }
            if(astudentBadgeid.getTimeOut()!=0)
            {
                //可以返回了
                if(astudentBadgeid.getTimeOut()>catsdto.getLxydts())
                {
                    return Result.error("时间不足");
                }
            }
            /// 存储到勋章记录表
            AstudentBadge astudentBadge=new AstudentBadge();
            astudentBadge.setUserId(Math.toIntExact(loginId));
            astudentBadge.setBadgeType(astudentBadgeid.getBadegeName());
            astudentBadge.setAwardDate(LocalDate.now());
            astudentBadge.setStubadegeId(astudentBadgeid.getId());
            astudentBadgeService.save(astudentBadge);
            return Result.ok( );




        }




        return null;
    }
}
